#include <gio/gio.h>
#include <stdio.h>
#include "battery.h"

static batteryCab* skeleton=NULL;

static gboolean on_handle_set_name(batteryCab* skeleton,GDBusMethodInvocation *invocation,const gchar *str,gpointer user_data)
{
    printf("Method call: %s\n", str);
    battery_cab_complete_set_name (skeleton, invocation);
    return TRUE;
}

static gboolean on_handle_get_version(batteryCab* skeleton,GDBusMethodInvocation *invocation,const gchar *str,gpointer user_data)
{
    printf("Method call: %s\n", str);
    battery_cab_complete_get_version (skeleton, invocation, "V1.5");
    return TRUE;
}


void on_bus_acquired (GDBusConnection *connection,const gchar *name,gpointer user_data)
{
    printf("on_bus_acquired has been invoked, name is %s\n", name);
    GError *error = NULL;
    skeleton = battery_cab_skeleton_new();

    g_signal_connect(skeleton,"handle-set-name", G_CALLBACK(on_handle_set_name),NULL);
    g_signal_connect(skeleton,"handle-get-version", G_CALLBACK(on_handle_get_version),NULL);

    g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(skeleton), connection, "/cygia/battery/cab", &error);
    if(error != NULL){                                                           
        printf("Error: Failed to export object. Reason: %s.\n", error->message);
        g_error_free(error);                                                    
    }
}

void on_bus_name_acquired (GDBusConnection *connection,const gchar *name,gpointer user_data)
{
    printf("on_bus_name_acquired has been invoked\n");
}


void on_bus_name_lost (GDBusConnection *connection,const gchar *name,gpointer user_data)
{
    printf("on_bus_name_lost !!!!\n");
}

static gint status_value = 1;
static gboolean emit_test_status_signal(gconstpointer p)
{
    printf("emit_test_status_signal invoked\n");
    if(skeleton != NULL)
    {
        battery_cab_emit_test_status(skeleton, status_value);
    }
    status_value ++;
    return 1;
}

int main(int argc, char const *argv[])
{
    guint owner_id;
    GMainLoop *loop;
    #if !GLIB_CHECK_VERSION(2,35,0)
    g_type_init();
    #endif
    printf("glib version: %d.%d.%d\n", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
    owner_id = g_bus_own_name(G_BUS_TYPE_SESSION,
                            "cygia.battery.cab",
                            G_BUS_NAME_OWNER_FLAGS_NONE,
                            on_bus_acquired,
                            on_bus_name_acquired,
                            on_bus_name_lost,
                            NULL,
                            NULL);

    //test status signal every 3 seconds
    g_timeout_add(3000,(GSourceFunc)emit_test_status_signal,NULL);

    // main loop
    loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(loop);

    g_bus_unown_name(owner_id);

    return 0;
}

